//
//  XGAdvertiseViewController.swift
//  Funny
//
//  Created by monkey on 2019/9/11.
//  Copyright © 2019 itcast. All rights reserved.
//

import UIKit
import SDWebImage

/// 跳过广告通知名称
public let XGSkipAdvertiseNotification = "XGSkipAdvertiseNotification"

class XGAdvertiseView: UIView
{
    // MARK: - 构造方法
    
    override init(frame: CGRect)
    {
        super.init(frame: frame)
        setUpUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func willMove(toSuperview newSuperview: UIView?)
    {
        if newSuperview != nil {
            // 添加到父视图
            loadAdvertise()
        } else {
            // 从父视图移除
        }
    }
    
    deinit {
        XGPrint("广告视图回收")
    }
    
    // MARK: - 私有属性
    
    private lazy var imageView:UIImageView = {
        let path = Bundle.main.path(forResource: "LaunchImageiPhonePortrait.png", ofType: nil)!
        let imageView = UIImageView(image: UIImage(contentsOfFile: path))
        imageView.contentMode = .scaleAspectFill
        imageView.clipsToBounds = true
        return imageView
    }()
    
    /// 跳过按钮
    private lazy var skipButton:UIButton = UIButton(title: "跳过 3", normalColor: UIColor.white, highlightedColor: UIColor.white, fontSize: 17, backgroundImageName: nil, backgroundColor: UIColor(white: 0.2, alpha: 1), imageName: nil, target: self, action: #selector(skipAction))
    /// 定时器
    private var timer:Timer?
    /// 广告停留时间
    private var seconds:Int = 3
}

private extension XGAdvertiseView
{
    /// 跳过事件
    @objc func skipAction() -> Void
    {
        self.timer?.invalidate()
        self.timer = nil
        NotificationCenter.default.post(name: Notification.Name(rawValue: XGSkipAdvertiseNotification), object: nil, userInfo: nil);
    }
    
    func setUpUI() -> Void
    {
        backgroundColor = UIColor.white
        
        addSubview(imageView)
        addSubview(skipButton)
        skipButton.isHidden = true
        
        imageView.snp_makeConstraints { (make) in
            make.edges.equalTo(self)
        }
        
        skipButton.snp_makeConstraints { (make) in
            make.top.equalTo(self).offset(30)
            make.right.equalTo(self).offset(-30)
            make.size.equalTo(CGSize(width: 80, height: 40))
        }
    }
    
    // 加载广告
    func loadAdvertise() -> Void
    {
        XGTopicDAL.shared.loadAdvertisement { (responseObject, error) in
            if responseObject == nil {
                XGPrint("加载广告失败")
                NotificationCenter.default.post(name: Notification.Name(rawValue: XGSkipAdvertiseNotification), object: nil, userInfo: nil);
                return
            }
            
            let advertiseModel = XGAdvertiseModel.mj_object(withKeyValues: responseObject)
            SDWebImageManager.shared().loadImage(with: URL(string: advertiseModel?.w_picurl ?? ""), options: [], progress: nil, completed: { (image, _, _, _, _, url) in
                if let image = image {
                    DispatchQueue.once(token: url?.absoluteString ?? "advertise", block: {
                        self.showAdvertise(image: image)
                    })
                }
            })
        }
    }
    
    // 展示广告
    func showAdvertise(image:UIImage) -> Void
    {
        skipButton.isHidden = false
        self.imageView.image = image
        timer = Timer(timeInterval: 1, repeats: true) { [weak self](_) in
            if self?.seconds == 0 {
                XGPrint("停止")
                self?.timer?.invalidate()
                self?.timer = nil
                NotificationCenter.default.post(name: Notification.Name(rawValue: XGSkipAdvertiseNotification), object: nil, userInfo: nil);
                return
            }
            self?.seconds -= 1
            self?.skipButton.setTitle("跳过 " + "\(self?.seconds ?? 0)", for: .normal)
        }
        RunLoop.current.add(timer!, forMode: .common)
    }
}
